using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using System.Xml;

namespace AppConfigEditor {
    /// <summary>
    /// Helper class
    /// ConfigReader will process XML document's nodes and build XPath map.
    /// </summary>
    internal class ConfigReader {

        Dictionary<string, string> nodesList = new Dictionary<string, string>();
        StringBuilder xPath = new StringBuilder();
        Dictionary<string, string > nodeNames = new Dictionary <string, string >();

        /// <summary>
        /// Get an array of XPath from document
        /// </summary>
        /// <param name="path">xml document path</param>
        /// <returns></returns>
        public string[] GetNodes(string path) {
            try {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(path);
                xPath.Append("//");
                foreach (XmlNode node in xDoc.ChildNodes) {
                    GetNode(node);
                }
            } catch (Exception ex) {
                Console.Out.WriteLine("error:" + ex.Message);
            }
            
            List<string>tmpList = new List<string>();
            foreach(string k in nodeNames.Keys){
                tmpList.Add(nodeNames[k].ToString());
            }
            //sort elements in the list
            tmpList.Sort();
            return tmpList.ToArray();
        }

        /// <summary>
        /// Walk through document and pick up XPath to each node
        /// </summary>
        /// <param name="node"></param>
        void GetNode(XmlNode node) {
            int index = xPath.Length;
            xPath.Append(node.Name + "/");
            //Console.Out.WriteLine("Parent: {0}\n", xPath.ToString());
            foreach (XmlNode n in node.ChildNodes) {
                //Console.Out.WriteLine("Node name:'{0}{1}'", n.Name, n.HasChildNodes == true ? "/" : "");
                if (n.NodeType == XmlNodeType.Element) {
                    foreach (XmlAttribute at in n.Attributes) {
                        //Console.Out.WriteLine("\tattribute:'{0}' value:'{1}'", at.Name, at.Value);
                    }
                    if (n.HasChildNodes) {
                        GetNode(n);
                    }
                }
            }
            //Remove last character '/'
            xPath.Remove(index, node.Name.Length + 1);
            try{
                if(!nodeNames.Keys.Equals(xPath.ToString())){
                    string xpath = xPath.ToString();//.Substring(0, xPath.Length - 1);
                    if (!xPath.ToString().Equals("//")) {
                        nodeNames.Add(xPath.ToString(), xpath);
                    }
                }
            }catch{}
        }        
    }
}
